const { cloneDeep } = require('lodash');

class QueryBuilder {
    constructor(model, chain = []) {
        this.model = model;    // 关联的Entity
        this._chain = [...chain];  // 操作链（关键改进：每次操作都生成新实例）
        this._state = {        // 分离状态存储
            select: ['*'],
            where: [],
            params: [],
            orders: [],
            limit: null,
            offset: null,
            withDeleted: false
        };
    }

    // 核心方法：生成新实例并记录操作
    _chainCall(fn) {
        const newBuilder = new QueryBuilder(this.model, [...this._chain, fn]);
        newBuilder._state = cloneDeep(this._state);
        fn.call(newBuilder, newBuilder._state);
        return newBuilder;
    }

    // SELECT 字段控制
    select(...fields) {
        return this._chainCall(state => {
            state.select = fields.length > 0 ? fields : ['*'];
        });
    }

    clearSelect() {
        return this.select('*');
    }

    // WHERE 条件
    where(field, operator, value) {
        return this._chainCall(state => {
            const op = this._parseOperator(operator);
            state.where.push(`${field} ${op}`);
            state.params.push(this._formatValue(value, operator));
        });
    }

    first() {
        return this._chainCall(state => {
            state.limit = 1;
        });
    }

    // 分页控制
    paginate(page = 1, perPage = 15) {
        return this._chainCall(state => {
            state.limit = perPage;
            state.offset = (page - 1) * perPage;
        });
    }

    // 执行查询（终极方法）
     execute() {
        const sql = this._buildSQL();
        // console.log(sql.bgBlue);
        // console.log(JSON.stringify(this._state.params).bgCyan);

        const stmt = this.model.db.prepare(sql);
        // console.log('stmt::', stmt);
        // console.log('params::', this._state.params);
        return stmt.all(...this._state.params);
    }

    // 获取总数（不会触发死循环）
     getTotal() {
        const countQuery = new QueryBuilder(this.model);
        countQuery._state = cloneDeep(this._state);
        countQuery._state.select = ['COUNT(*) as total'];

        const result = countQuery.execute();
        return result[0]?.total || 0;
    }

    // SQL构造器（核心引擎）
    _buildSQL() {
        let sql = `SELECT ${this._state.select.join(', ')} FROM ${this.model.tableName}`;

        if (this._state.where.length > 0) {
            sql += ` WHERE ${this._state.where.join(' AND ')}`;
        }

        if (this._state.orders.length > 0) {
            sql += ` ORDER BY ${this._state.orders.join(', ')}`;
        }

        if (this._state.limit !== null) {
            sql += ` LIMIT ${this._state.limit}`;
            if (this._state.offset !== null) {
                sql += ` OFFSET ${this._state.offset}`;
            }
        }
        // console.log('finally sql::', sql);
        return sql;
    }

    // 包含已删除记录
    withDeleted() {
        return this._chainCall(state => {
            // 移除现有的软删除条件
            this._removeSoftDeleteCondition();
        });
    }

    // 排除已删除记录（默认）
    withoutDeleted() {
        return this._chainCall(state => {
            // 先移除现有的软删除条件
            this._removeSoftDeleteCondition();
            // 添加新的未删除条件
            state.where.push(`${this.model.softDeleteField} = ?`);
            state.params.push(this.model.constructor.STATUS.DELETE_STATUS.ACTIVE);
        });
    }

    // 私有方法：移除现有的软删除条件
    _removeSoftDeleteCondition() {
        const softDeleteField = this.model.softDeleteField;
        const newWhere = [];
        const newParams = [];

        // 重建where和params，跳过软删除条件
        this._state.where.forEach((cond, index) => {
            if (!cond.includes(softDeleteField)) {
                newWhere.push(cond);
                newParams.push(this._state.params[index]);
            }
        });

        this._state.where = newWhere;
        this._state.params = newParams;
    }

    // 专门查询已被软删除的记录（回收站数据）
    recycled() {
        return this._chainCall(state => {
            // 1. 先移除可能存在的软删除条件
            this._removeSoftDeleteCondition();
            // 2. 添加"已删除"条件
            state.where.push(`${this.model.softDeleteField} = ?`);
            state.params.push(this.model.constructor.STATUS.DELETE_STATUS.DELETED);
        });
    }

    // 操作符解析（安全校验）
    _parseOperator(op) {
        const operatorMap = {
            '$eq': '= ?',
            '$ne': '!= ?',
            '$gt': '> ?',
            '$gte': '>= ?',
            '$lt': '< ?',
            '$lte': '<= ?',
            '$like': 'LIKE ?'
        };

        if (!operatorMap[op]) throw new Error(`Invalid operator: ${op}`);
        return operatorMap[op];
    }

    // 参数格式化（防注入）
    _formatValue(value, operator) {
        if (operator === '$like') return `%${value}%`;
        if (typeof value === 'boolean') return value ? 1 : 0;
        return value;
    }
}

module.exports = QueryBuilder;